<?php
namespace app\admin\controller;

use app\admin\model\AttachmentModel;
use think\Db;
class Attachment extends Base
{
	public function index(){
		if(request()->isAjax()){
			$param = input('param.');
			$limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
			$Model = new AttachmentModel();
			$return['rows'] = $Model->getInfoByWhere('',true,$offset,$limit,'create_time desc');

			foreach ($return['rows'] as $k => $v){
				$return['rows'][$k]['create_time'] = date("Y-m-d H:i:s",$v['create_time']);
				$return['rows'][$k]['size'] = sprintf("%.4f", ($v['size'] / 1024 / 1024));
				if($v['status'] == 1){
					$return['rows'][$k]['statusText'] = '<span class="btn btn-primary btn-sm"'
													  . 'data-param="'. $v['id'] .'"'
													  . 'data-setstatus="setAttachStatus"'
													  . '>启用</span>';
				}else{
					$return['rows'][$k]['statusText'] = '<span class="btn btn-danger btn-sm"'
													  . 'data-param="'. $v['id'] .'"'
													  . 'data-setstatus="setAttachStatus"'
													  . '>禁用</span>';
				}
			}
			$return['total'] = count($Model->getInfoByWhere('',false));
			return json($return);
		}
		return $this->fetch();
	}

	public function setAttachStatus(){
		$id = json_decode(input('post.param'));
		$attach = new AttachmentModel($id);
		$return = $attach->setstatus($id);
		return $return;
	}

	public function uploadAttach(){
		if (!isset($_FILES["file"])||empty($_FILES["file"])) {
            return ['code'=>0,'msg'=>'没有上传文件'];
        } else {
            $name = $_FILES["file"]["name"];
            $ext = explode('.',$name);
            $ext = $ext[sizeof($ext)-1];
            $size = $_FILES["file"]["size"];
            $tmp = $_FILES["file"]["tmp_name"];
            $data_ext = explode(',', input('data_ext'));
            if($data_ext[0] != 'null'){
            	foreach($data_ext as $vext){
            		if(!in_array($vext, config('ext'))){
	            		return ['code' => 0,'msg' => '文件格式错误'];
	            	}
            	}
            	if(!in_array($ext, $data_ext)){
            		return ['code' => 0,'msg' => '文件格式错误'];
            	}
            }
            if (in_array($ext,config('ext'))){
                if ($size <= config('max_size_of_upload')){
                    $time = strtotime(date("Y-m-d"));
					$path = "upload/attachments/".session('username').session('id')."/".$time;
                    try {
                        if (!is_dir($path)) {
                            mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
                        }
                        if(input('get.targetpath') == ''){
                        	$save = $path."/".session('username').session('id')."'s".time().rand(1000,9999).'.'.$ext;
                        	$db_name = session('username') . session('id') . "'s" .time();
                        }else{
                        	$save = "upload/".input('get.targetpath').'.'.$ext;
                        	$db_name = explode('/',input('get.targetpath'));
                        	$db_name = $db_name[sizeof($db_name)-1];
                        	DB::name('attachment')->where('path',$save)->delete();
                        }

						$url = "/" . $save;
                        if (move_uploaded_file($tmp, $save)) {
                            $id = DB::name('attachment')->insertGetId([
                            	"name"=>$db_name,
                            	"path"=>$save,
                            	"size"=>$size,
                            	"ext"=>$ext,
                            	"url"=>$url,
                            	"create_time"=>time(),
                            	'create_uid'=>session('id')
                            ]);
                            return ['code'=>1,'msg'=>' 上传成功','data'=>['id'=>$id,'path'=>$url]];
                        }
                    } catch (Expectation $e) {
                        return ['code'=>0,'msg'=>'上传失败'.$e->getMessage()];
                    }

                } else {
                    return ['code'=>0,'msg'=>'上传文件过大'];
                }
            } else {
                return ['code'=>0,'msg'=>"上传格式不被允许"];
            }
        }
	}

	public function delAttach($param){
		$ids = json_decode($param);

		DB::startTrans();
		try{
			foreach($ids as $v){
				$path = DB::name('attachment')->where('id',$v)->value('path');
				DB::name('attachment')->where('id',$v)->delete();
				unlink(APP_PATH."../public/".$path);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功'];
		}catch(Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
		}

	}

	/**
	 * [上传附件弹窗视图]
	 */
	public function uploadfile(){
		$this->assign([
			'multiple'=>input('get.multiple'),
			'targetpath'=>input('get.targetpath'),
			'action'=>input('get.action'),
			'data_ext'=>input('data_ext'),
		]);
		return $this->fetch();
	}

	public function setlogo(){
		$id = input('post.id');
		if(DB::name('webset')->where('name','logo')->update(['values'=>$id])){
			return ['code'=>1,'msg'=>'更新成功'];
		}else{
			return ['code'=>0,'msg'=>'更新失败'];
		}
	}
	public function setmini_logo(){
		$id = input('post.id');
		if(DB::name('webset')->where('name','mini_logo')->update(['values'=>$id])){
			return ['code'=>1,'msg'=>'更新成功'];
		}else{
			return ['code'=>0,'msg'=>'更新失败'];
		}
	}
	/**
	 * [上传学生一寸照片]
	 */
	public function uploadIdPhoto(){
		$id = input('post.id');
		$attachModel = new AttachmentModel();
		$st_id = explode("_",$attachModel->getAttachmentPath($id,'name'))[1];
		$data = [
			'id_photo' => $id,
			'id_photo_url' => $attachModel->getAttachmentPath($id,'url')
		];
		if(DB::name('student')->where('id',$st_id)->update($data)){
			return ['code'=>1,'msg'=>'更新成功'];
		}else{
			return ['code'=>0,'msg'=>'更新失败'];
		}
	}
	/**
	 * [上传客户一寸照片]
	 * $id 上传附件的id值
	 * $st_id 客户id值
	 */
	public function uploadMemberPhoto(){
		$ids = input('param.');
		$memFile = DB::name('member')->where(['id'=>$ids['mid']])->field('id_photo,id_photo_url')->find();
		$attachModel = new AttachmentModel();
		$data = [
			'id_photo' => $memFile['id_photo'].','.$ids['id'],
			'id_photo_url' => $memFile['id_photo_url'].','.$attachModel->getAttachmentPath($ids['id'],'url')
		];
		if(DB::name('member')->where('id',$ids['mid'])->update($data)){
			return ['code'=>1,'msg'=>'更新成功'];
		}else{
			return ['code'=>0,'msg'=>'更新失败'];
		}
	}
}
